#include <unistd.h>
#import "CustomTable.h"
#import "CustomTableCell.h"
#import "SetupView.h"
#import "CDList.h"

@implementation CDList : UIView

- (id) initWithApplication: (UIApplication*)app withAppID: (NSString*)appID withFrame: (struct CGRect)rect
{
	//NSLog(@"CDList: initWithApplication a\n");
	//Init view with frame rect
	[super initWithFrame: rect];
	
	//Save application object
	_application = app;
	_applicationID = appID;
	
	//Set Count Down List path
	NSString* pathTo_CountDown = @"/var/root/Library/iCountDown";
	_fileManager = [NSFileManager defaultManager];
	if (![_fileManager fileExistsAtPath:pathTo_CountDown])
	{
		// /var/root/Library/CountDown doesn't exist so create the path
		[_fileManager createDirectoryAtPath:pathTo_CountDown attributes: nil];
	}
	//set path and file name to counters information
	_pathToCountersSaved = @"/var/root/Library/iCountDown/iCountDowns.plist";
	
	//set the counter font
	_counterFont = [NSClassFromString(@"WebFontCache") createFontWithFamily: @"Helvetica" traits: 2 size: 40];
	
	//Setup nav bar for Count Down View
	float navBarWidth = rect.size.width;
	float navBarHeight = 50.0f;
	float defaultButtonHeight = 32.0f;
	
	_navbar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, navBarWidth, navBarHeight)];
	UINavigationItem* title = [[UINavigationItem alloc] initWithTitle:@"iCountDown"];
	[_navbar pushNavigationItem:title];
	[_navbar setBarStyle: 0];
	[_navbar enableAnimation];
	
	//Setup Edit button
	_editButton = [[UINavBarButton alloc] initWithFrame: CGRectMake(10.0f, 10.0f, 50.0f, defaultButtonHeight)];
	[_editButton setAutosizesToFit: FALSE];
	[_editButton setTitle: @"Edit"];
	[_editButton addTarget: self action: @selector(editCountDown) forEvents: 1];
	[_editButton setNavBarButtonStyle: 0];
	
	//Setup Add button
	_addButton = [[UINavBarButton alloc] initWithFrame: CGRectMake(rect.size.width - 53.0f, 10.0f, 35.0f, defaultButtonHeight)];
	[_addButton setAutosizesToFit: FALSE];
	[_addButton setTitle: @"+"];
	[_addButton addTarget: self action: @selector(addNewCountDown) forEvents: 1];
	[_addButton setNavBarButtonStyle: 0];
	
	// add the NAV bar buttons to the view
	[_navbar addSubview: _addButton];
	[_navbar addSubview: _editButton];
	
	//Setup CounterList (A Table Wrapper)
	_selectedCellIndex = -1;
	
	rect.size.height -= 50.0f;
	rect.origin.y = 50.0f;
	
	//Setup Counters
	[self initCounterListFromCounterDir];
	[self refreshCounterList];
	
    _counterTable = [[CustomTable alloc] initWithFrame:rect andArray: _counterCells andList: self];
	
	UITableColumn *myColumn = [[UITableColumn alloc] initWithTitle:@"CountDown" identifier:@"CountDown" width:rect.size.width];
	[_counterTable addTableColumn:myColumn];
	[_counterTable setSeparatorStyle:1];
	[_counterTable setRowHeight:100.0f];
	[_counterTable setShowScrollerIndicators:NO];
//	[_counterTable setAllowsReordering:YES]; // set to no if reordering isn't wanted
//	[_counterTable enableRowDeletion: YES animated: YES];
	int i;
	for(i=0;i<[_theCounters count];i++)
	{
		[[_counterTable visibleCellForRow:i column:0] _showDeleteOrInsertion:NO withDisclosure:NO animated:NO isDelete:NO andRemoveConfirmation:NO];
	}

	[self addSubview: _navbar];
	[self addSubview: _counterTable];
/*
	float translucentBlack[4] = {0, 0, 0, .93};
	float transparent[4] = {0, 0, 0, 0};
	float white[4] = {1, 1, 1, 1};
	float black[4] = {0, 0, 0, 1};	
	struct CGSize offset;
	offset.height = 1.0f;
	offset.width = 1.0f;
*/	
	
    // create our timer
	double tickIntervalM = 0.2;
    _timerM = [NSTimer scheduledTimerWithTimeInterval: tickIntervalM
                target: self
                selector: @selector(displaytick:)
                userInfo: nil
                repeats: YES];
				
	return self;
}

// allow access to the setup view of counters
- (void) setSetupAccess: (SetupView *) theView
{
	_setupView = theView;
}

//save the counters into a plist file
- (void) saveCounters
{
	//create the dictionary
	NSMutableDictionary *thedictionary = [NSMutableDictionary new];
	
	//place the number of counters in the dictionary
	//NSLog(@"CDList: saveCounters a\n");
	[thedictionary setObject:[[NSNumber alloc]  initWithInt: [_theCounters count]] forKey:KEY_COUNTER_COUNT]; 
	
	//place all the counters into the dictionary
	int i;
	for (i = 0;i<[_theCounters count];i++)
	{
		//save counter name
		[thedictionary setObject:[_theCounterName objectAtIndex:i] forKey: [[NSString alloc] initWithFormat:@"%@ %i",KEY_COUNTER_NAME,i]]; 
		
		//save counter date
		[thedictionary setObject:[_theCounters objectAtIndex:i] forKey: [[NSString alloc] initWithFormat:@"%@ %i",KEY_COUNTER_VALUE,i]]; 
		
		//save counter display type
		[thedictionary setObject:[_theCounterDisplayType objectAtIndex:i] forKey: [[NSString alloc] initWithFormat:@"%@ %i",KEY_COUNTER_DTYPE,i]]; 
		
		//save the counter direction
		[thedictionary setObject:[_theCounterIsNegative objectAtIndex:i] forKey: [[NSString alloc] initWithFormat:@"%@ %i",KEY_COUNTER_NEGATIVE,i]];
		
		//save the prompted state
		[thedictionary setObject:[_theCounterPromptedExpired objectAtIndex:i] forKey: [[NSString alloc] initWithFormat:@"%@ %i",KEY_COUNTER_PROMPTED,i]];

	}
	
	//delete the old counter file
	[_fileManager removeFileAtPath: _pathToCountersSaved handler:nil];
	
	//write the new counter dictionary to the file
	[thedictionary writeToFile: _pathToCountersSaved atomically:YES];
	
	[thedictionary release];
}

//init the counters or read them in from the user plist file
- (void) initCounterListFromCounterDir
{
	
	// init the counter info
	_theCounters = [[NSMutableArray alloc] init];
	_theCounterName = [[NSMutableArray alloc] init];
	_theCounterDisplayType = [[NSMutableArray alloc] init];
	_theCounterIsNegative = [[NSMutableArray alloc] init];
	_theCounterPromptedExpired = [[NSMutableArray alloc] init];
	
	// open up the file manager to the count down library directory
	[_fileManager changeCurrentDirectoryPath: _pathToCountersSaved];
	
	// check to see if the counters saved file is present
	if ([_fileManager isReadableFileAtPath: _pathToCountersSaved])
	{

		// Open the plist
		NSMutableDictionary* plistDict = [NSMutableDictionary dictionaryWithContentsOfFile: _pathToCountersSaved];
				
		// read in the the number of counters
   	    int countercount = [[plistDict objectForKey:KEY_COUNTER_COUNT] intValue];
		//NSLog(@"CDList: initCounterListFromCounterDir a cnt:%d\n",countercount);
		
		int i;
		for(i=0; i < countercount; i++)
		{
			//get counter name
			[_theCounterName addObject: [plistDict objectForKey:[[NSString alloc] initWithFormat:@"%@ %i",KEY_COUNTER_NAME,i]]];

			//get counter date
			[_theCounters addObject: [plistDict objectForKey:[[NSString alloc] initWithFormat:@"%@ %i",KEY_COUNTER_VALUE,i]]];
		
			//get counter display type
			[_theCounterDisplayType addObject: [plistDict objectForKey:[[NSString alloc] initWithFormat:@"%@ %i",KEY_COUNTER_DTYPE,i]]];
			
			//get counter direction of count
			[_theCounterIsNegative addObject:  [plistDict objectForKey:[[NSString alloc] initWithFormat:@"%@ %i",KEY_COUNTER_NEGATIVE,i]]];

			//get the prompted state of the counter
			[_theCounterPromptedExpired addObject:  [plistDict objectForKey:[[NSString alloc] initWithFormat:@"%@ %i",KEY_COUNTER_PROMPTED,i]]];
		}			
	} 
	else 
	{
		// init to one counter and offset the counter one MOON
		double v = MOON_SECONDS;
		[ _theCounters addObject: [[NSDate alloc] initWithTimeIntervalSinceNow:v]];
		[ _theCounterName addObject: [[NSString alloc] initWithFormat:@"Counter: 1"]]; 
		[ _theCounterDisplayType addObject : [[NSNumber alloc] initWithInt: 1]];
		[ _theCounterIsNegative addObject : [[NSNumber alloc] initWithBool: TRUE]];
		[ _theCounterPromptedExpired addObject: [[NSNumber alloc] initWithBool: FALSE]];
		//save it off, to create a plist file
		[self saveCounters];
	}
	
}

//allow display of an error message
- (void) raiseAlert: (NSString*)msg
{
	NSString *nscmd = [NSString stringWithFormat:@"'%@'", msg];
	const char *cmd = [nscmd UTF8String];
	system(cmd);
}

//place the counters into the table for display
- (void) refreshCounterList
{

	//remove all the current counters
	[_counterCells release];
	_counterCells = [[NSMutableArray alloc] init];
	
	//Create a dictionary object for the headers
	CustomTableCell* cell;
	
	// Setup all the active counters into table cells
	int i = 0;
	NSTimeInterval t;
	while (i < [_theCounters count])
	{						
		//setup the counter display in the UI display	
		cell = [[CustomTableCell alloc] init];
		[cell setCounterName: [_theCounterName objectAtIndex: i]];
		[cell setDisplayType: [_theCounterDisplayType objectAtIndex: i]];	
		[cell setSeconds: [NSString localizedStringWithFormat:@"Loading...."] withSpecial: [NSString localizedStringWithFormat:@" "]];	
		[cell setEnableReordering:YES animated:YES];
		[_counterCells addObject: cell];

		i += 1;
		[cell release];
	}	
}

- (void) setDelegate: (id)delegate;
{
	//NSLog(@"cdlist: setDelegate\n");
	_delegate = delegate;	
}

// this is the timer routine called every timer tick
- (id) displaytick: (NSTimer *)timer
{

  //NSLog(@"cdlist: timer\n");
  NSTimeInterval interval;
  double val;
  int days;
  int hours;
  int minutes;
  int moons;
  double seconds;
  int i; 
  i = 0; 
  BOOL minus;
  while( i <  [_theCounters count] )
  {
	// get the number of seconds to counter
	interval = [[_theCounters objectAtIndex:i] timeIntervalSinceNow];
	minus = FALSE;
	
	if (interval < 0.0f)
	{
		//make sure that counters going to 0, stick
		if ( [[_theCounterIsNegative objectAtIndex:i] boolValue] == FALSE)
		{
			interval = 0.0f;
			
			if ( [[_theCounterPromptedExpired objectAtIndex: i] boolValue] == FALSE )
			{
				NSArray *buttons = [NSArray arrayWithObjects:@"Close", nil];
				UIAlertSheet *myAlert = [[[UIAlertSheet alloc] initWithTitle:[_theCounterName objectAtIndex: i] buttons:buttons defaultButtonIndex:1 delegate:self context:@"Method to identify this alertsheet"] autorelease];
				[myAlert setBodyText:@"Your Counter Expired"];
				[myAlert setRunsModal:NO];
				[myAlert popupAlertAnimated:YES];
				[_theCounterPromptedExpired replaceObjectAtIndex:i withObject:[[NSNumber alloc] initWithBool: TRUE]];
			}
		}
		// negative counters remain so forever
		else
		{
			minus = TRUE;
			interval = interval*(-1.0);
		}
	}
	//if a positive counter, set the flag properly
	else
	{
		[_theCounterIsNegative replaceObjectAtIndex:i withObject:[[NSNumber alloc] initWithBool: FALSE]];
	}
	
	//change the counter display in the UI display	
	
	//organize time for display
	switch([[_theCounterDisplayType objectAtIndex:i] intValue])
	{
	// Days
	case 0:
		days = interval/ DAY_SECONDS;
		val = days;
		hours = (interval - val*DAY_SECONDS) / HOUR_SECONDS;
		minutes = (interval - val*DAY_SECONDS - hours*HOUR_SECONDS) / MINUTE_SECONDS;
		seconds = interval - val*DAY_SECONDS - hours*HOUR_SECONDS - minutes*MINUTE_SECONDS;
		if (minus)
		{
			[[_counterCells objectAtIndex:i] setSeconds:[NSString localizedStringWithFormat:@"%02d:%02d:%04.1f",hours,minutes,seconds]
			 withSpecial: [NSString localizedStringWithFormat:@"-%05d:",days] ];
		}
		else
		{
			[[_counterCells objectAtIndex:i] setSeconds:[NSString localizedStringWithFormat:@"%02d:%02d:%04.1f",hours,minutes,seconds]
			 withSpecial: [NSString localizedStringWithFormat:@"%05d:",days] ];
		}
		break;
	//seconds
	case 1:
		if (minus)
		{
			[[_counterCells objectAtIndex:i] setSeconds: [NSString localizedStringWithFormat:@"-%013.1f",interval]
			 withSpecial: [NSString localizedStringWithFormat:@" "] ];
		}
		else
		{
			[[_counterCells objectAtIndex:i] setSeconds: [NSString localizedStringWithFormat:@"%013.1f",interval]
			 withSpecial: [NSString localizedStringWithFormat:@" "] ];
		}
		break;
	//moons - full	
	case 2:
		moons = interval/MOON_SECONDS;
		days = (interval - moons*MOON_SECONDS)/ DAY_SECONDS;
		hours = (interval  - moons*MOON_SECONDS - days*DAY_SECONDS) /HOUR_SECONDS;
		minutes = (interval - moons*MOON_SECONDS - days*DAY_SECONDS - hours*HOUR_SECONDS) / MINUTE_SECONDS;
		seconds = interval  - moons*MOON_SECONDS - days*DAY_SECONDS - hours*HOUR_SECONDS - minutes*MINUTE_SECONDS;
		if (minus)
		{
			[[_counterCells objectAtIndex:i] setSeconds: [NSString localizedStringWithFormat:@"%02d:%02d:%02d:%04.1f",days,hours,minutes,seconds]
			 withSpecial: [NSString localizedStringWithFormat:@"-%04d:",moons]];
		}
		else
		{
			[[_counterCells objectAtIndex:i] setSeconds: [NSString localizedStringWithFormat:@"%02d:%02d:%02d:%04.1f",days,hours,minutes,seconds]
			 withSpecial: [NSString localizedStringWithFormat:@"%04d:",moons]];
		}
		break;
	}		
	i++;
  }
  [_counterTable myReloadData];
  
}

- (void)alertSheet:(UIAlertSheet*)sheet buttonClicked:(int)button
{
  if ( button == 1 ){
    [sheet dismiss];
  }
}


//set the display type for the count down
- (void) setSelectedCounterDisplayType: (NSNumber *)dtype
{
	[_theCounterDisplayType replaceObjectAtIndex:_selectedCellIndex withObject: dtype];

	// set the table entry
	[[_counterCells objectAtIndex:_selectedCellIndex] setDisplayType: dtype];
}

//get the display type for the count down
- (int) getSelectedCounterDisplayType
{
	if (_selectedCellIndex>-1)
	{
		return [[_theCounterDisplayType objectAtIndex:_selectedCellIndex] intValue];
	}
	return 0;
}

//get the Name for the count down
- (NSString *) getSelectedCounterName
{
	if (_selectedCellIndex>-1)
	{
		return [_theCounterName objectAtIndex:_selectedCellIndex];
	}
	return [[NSString alloc] initWithFormat:@"none"];
}

//set the Name for the count down
- (void) setSelectedCounterName: (NSString *)theName
{
	//change the counter name to the edited one
	[_theCounterName replaceObjectAtIndex:_selectedCellIndex withObject: theName];
	
	// set the table entry
	[[_counterCells objectAtIndex:_selectedCellIndex] setCounterName: theName];
}

//set the selected counter to the new value
- (void) setEditedCounter: (NSDate *)theEditedCounter
{	
  //only change the counter if edit has changed it
  if ( ! [theEditedCounter isEqualToDate: [_theCounters objectAtIndex:_selectedCellIndex]])
  {
	//change the counter to the edited one
	[_theCounters replaceObjectAtIndex:_selectedCellIndex withObject: theEditedCounter];
  }
}

//called by the setup view to get the counters back onto the display
- (void) redisplayCountDowns
{
	//place the count down list back onto the display
	[self addSubview: _navbar];
	[self addSubview: _counterTable];
	//check for a pos/neg counter and then set the flag before saving the setting
	NSTimeInterval interval;
	interval = [[_theCounters objectAtIndex:_selectedCellIndex] timeIntervalSinceNow];
	if (interval < 0.0)
	{
		[ _theCounterIsNegative replaceObjectAtIndex: _selectedCellIndex withObject: [[NSNumber alloc] initWithBool: TRUE]];
	}
	else
	{
		[ _theCounterIsNegative replaceObjectAtIndex: _selectedCellIndex withObject: [[NSNumber alloc] initWithBool: FALSE]];
	}
	[self saveCounters];
	[self displayTable];
	
    // create our timer
	double tickIntervalM = 0.2;
    _timerM = [NSTimer scheduledTimerWithTimeInterval: tickIntervalM
                target: self
                selector: @selector(displaytick:)
                userInfo: nil
                repeats: YES];
}

//prepare to edit a selected counter and change the view
- (void) editCountDown
{
  //check for a selected counter
  _selectedCellIndex = [_counterTable selectedRow];
  if ((_selectedCellIndex >-1)&&(_selectedCellIndex<[_theCounters count]))
  {
	//make sure timer is turned off
	[_timerM invalidate];
	[_navbar removeFromSuperview];
	[_counterTable removeFromSuperview];

	//launch edit window for counter
	//NSLog(@"cdlist: editCountDown %@\n",[[_theCounters objectAtIndex:_selectedCellIndex] class]);
	[self addSubview: _setupView];
    [_setupView makeSetupActive: [_theCounters objectAtIndex:_selectedCellIndex]];
	[_theCounterPromptedExpired replaceObjectAtIndex:_selectedCellIndex withObject:[[NSNumber alloc] initWithBool: FALSE]];
  }
}

//ADD(+) button pressed to add a new counter
- (void) addNewCountDown
{
  //make sure we have less than 4 counters
  if ([_theCounters count] < 4)
  {
	//make sure timer is turned off
	[_timerM invalidate];

	//default counter edit values
	int i = [_theCounters count];
	_selectedCellIndex = i;
	float v = MOON_SECONDS;
	[ _theCounters addObject: [[NSDate alloc] initWithTimeIntervalSinceNow:v]];
	[ _theCounterName addObject: [[NSString alloc] initWithFormat:@"Counter: %d",  i+1]];
	[ _theCounterPromptedExpired addObject : [[NSNumber alloc] initWithBool: FALSE]];
	[ _theCounterDisplayType addObject : [[NSNumber alloc] initWithInt: 1]];
	//regardless of the counter direction, the flag is the same
	[ _theCounterIsNegative addObject : [[NSNumber alloc] initWithBool: TRUE]];
	
	//place the new counter into a table cell object
	CustomTableCell* cell;
	cell = [[CustomTableCell alloc] init];
	[cell setCounterName: [_theCounterName objectAtIndex: i]];
	[cell setDisplayType: [_theCounterDisplayType objectAtIndex: i]];	
	[cell setSeconds: [NSString localizedStringWithFormat:@"Loading...."] withSpecial: [NSString localizedStringWithFormat:@" "]];	
	[cell setEnableReordering:YES animated:YES];
	[_counterCells addObject: cell];
	[cell release];
	
	//launch edit screen
	[_navbar removeFromSuperview];
	[_counterTable removeFromSuperview];

	//launch edit window for counter
	[self addSubview: _setupView];
	//NSLog(@"cdlist: addCountDown %d\n",i);
    [_setupView makeSetupActive: [_theCounters objectAtIndex:_selectedCellIndex]];
	}
	
}

//called to reload the custom table
- (void) displayTable
{
	[_counterTable reloadData];
}

//called to remove a table row, this is done when the custom table Delete button is pressed
- (void) removeRow: (int)row
{
	// remove the counter information for that row
	[_counterCells removeObjectAtIndex:row];
	[_theCounters removeObjectAtIndex:row];
	[_theCounterName removeObjectAtIndex:row];
	[_theCounterDisplayType removeObjectAtIndex:row];
	[_theCounterIsNegative removeObjectAtIndex:row];
	[_theCounterPromptedExpired removeObjectAtIndex:row];
	
	// save the changes to the counters
	[self saveCounters];
}

- (BOOL)respondsToSelector:(SEL)aSelector 
{
	//NSLog(@"respondsToSelector: selector = %@", NSStringFromSelector(aSelector));
	return [super respondsToSelector:aSelector];
}

@end
